import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Tooltip, Card, Form, Button, Table, Divider, message } from 'antd';
import dynamic from 'umi/dynamic';
import LoadingComponent from '@/components/PageLoading/index';
import request from '@/utils/request';
import styles from '../styles.less';
import SelectComponentAttr from './common/SelectComponentAttr';

const namespace = 'componentManage';

const ComponentAttrAdd = dynamic({
  loader: () => import('./ComponentAttrAdd'),
  loading: LoadingComponent,
});

function ComponentAttrAddInfo(props) {
  const [loading, setLoading] = useState(false);
  const [selectComponentAttrVisibleFlag, setSelectComponentAttrVisibleFlag] = useState(false); // 选择组件属性弹窗展示/隐藏标记
  const [excludeAttrIds, setExcludeAttrIds] = useState([]); // 选择组件属性弹窗查询排除已选属性id

  useEffect(() => {
    queryComponentAttrList();
  }, [props.componentAddType]);

  const queryComponentAttrList = () => {
    if (props.componentAddType === 'modify') {
      setLoading(true);
      request('pmc/pcms/componentAttr/queryList', {
        data: {
          componentId: props.selectComponent.componentId,
        },
      }).then(res => {
        if (res != null && res.success === true) {
          saveComponentAttrAddList(res.data);
          setLoading(false);
        } else if (res && res.errMessage) {
          message.error(res.errMessage);
        } else {
          message.error('查询失败');
        }
      });
    }
  };

  useEffect(() => {
    const tempExcludeIds = props.componentAttrAddList.map(item => {
      return item.attrId;
    });
    setExcludeAttrIds(tempExcludeIds);
  }, [props.componentAttrAddList]);

  // dva 保存列表里选中组件属性
  const saveSelectComponentAttr = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectComponentAttr`,
      payload: params,
    });
  };

  // dva 保存编辑组件属性新增弹窗展示/隐藏标记
  const saveComponentAttrAddVisibleFlag = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveComponentAttrAddVisibleFlag`,
      payload: params,
    });
  };

  // dva 保存组件属性新增类型
  const saveComponentAttrAddType = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveComponentAttrAddType`,
      payload: params,
    });
  };

  // dva 保存组件属性列表数据
  const saveComponentAttrAddList = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveComponentAttrAddList`,
      payload: params,
    });
  };

  // 编辑组件元素
  const handleEdit = record => {
    saveSelectComponentAttr(record);
    saveComponentAttrAddType('edit');
    saveComponentAttrAddVisibleFlag(true);
  };

  // 删除组件元素
  const handleRemove = record => {
    const tempComponentAttrList = props.componentAttrAddList.filter(item => {
      return item.attrId !== record.attrId;
    });
    saveComponentAttrAddList(tempComponentAttrList);
  };

  // 选择组件属性
  const handleSelectComponentAttr = () => {
    setSelectComponentAttrVisibleFlag(true);
  };

  // 选择组件属性回调函数
  const selectComponentAttrCallBacks = {
    selectComponentAttrCallBack: data => {
      const tempComponentAttrList = props.componentAttrAddList.concat(
        data.filter(item => {
          // delete item.createDate;
          // delete item.updateDate;
          return excludeAttrIds.indexOf(item.attrId) === -1;
        })
      );
      saveComponentAttrAddList(tempComponentAttrList);
    },
    handleVisibleFlag: flag => {
      setSelectComponentAttrVisibleFlag(flag);
    },
  };

  const cellStyle = {
    maxWidth: 200,
    overflow: 'hidden',
    whiteSpace: 'nowrap',
    textOverflow: 'ellipsis',
    cursor: 'pointer',
  };

  const columns = [
    {
      title: '属性名称',
      dataIndex: 'attrName',
      onCell: () => {
        return {
          style: cellStyle,
        };
      },
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '属性编码',
      dataIndex: 'attrNbr',
    },
    {
      title: '属性值',
      dataIndex: 'attrValue',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      onCell: () => {
        return {
          style: cellStyle,
        };
      },
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '操作',
      render: (text, record) => {
        return (
          <span>
            <a
              onClick={() => {
                handleEdit(record);
              }}
            >
              编辑
            </a>
            <Divider type="vertical" />
            <a
              onClick={() => {
                handleRemove(record);
              }}
            >
              删除
            </a>
          </span>
        );
      },
    },
  ];

  return (
    <div className={styles.card_body_no_adding}>
      <Card
        title="组件属性"
        className="cute"
        style={{ height: '100%' }}
        extra={
          <div>
            <Button
              type="primary"
              className="margin-right"
              onClick={() => handleSelectComponentAttr()}
            >
              新增组件属性
            </Button>
          </div>
        }
      >
        <Table
          rowKey={record => record.attrId}
          columns={columns}
          pagination={false}
          dataSource={props.componentAttrAddList}
          bordered
          loading={loading}
          rowClassName={record => {
            return record.attrId === props.selectComponentAttr.attrId ? styles.clickRowStyle : '';
          }}
          onRow={record => {
            return {
              onClick: () => {
                saveSelectComponentAttr(record);
              },
            };
          }}
        />
      </Card>
      {/* 编辑组件属性 */}
      {props.componentAttrAddVisibleFlag ? (
        <ComponentAttrAdd modalVisible={props.componentAttrAddVisibleFlag} />
      ) : null}
      {/* 选择组件属性 */}
      {selectComponentAttrVisibleFlag ? (
        <SelectComponentAttr
          modalVisible={selectComponentAttrVisibleFlag}
          excludeAttrIds={excludeAttrIds}
          {...selectComponentAttrCallBacks}
        />
      ) : null}
    </div>
  );
}

export default connect(({ componentManage, setting }) => ({
  selectComponentAttr: componentManage.selectComponentAttr,
  componentAttrAddVisibleFlag: componentManage.componentAttrAddVisibleFlag,
  componentAttrAddList: componentManage.componentAttrAddList,
  componentAddType: componentManage.componentAddType,
  selectComponent: componentManage.selectComponent,
  size: setting.size,
}))(Form.create()(ComponentAttrAddInfo));
